package com.hoshiicloud.shxping.jobhandler;

import com.hoshiicloud.common.constant.refund.RefundOrderStatusEnum;
import com.hoshiicloud.common.query.OmnipotentWrapper;
import com.hoshiicloud.common.rpc.Response;
import com.hoshiicloud.saleorder.entity.RefundOrder;
import com.hoshiicloud.saleorder.param.refund.RefundOrderCancelParam;
import com.hoshiicloud.shxping.feign.OrderFeignService;
import com.hoshiicloud.shxping.service.ShxpRefundOrderService;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.IJobHandler;
import com.xxl.job.core.handler.annotation.JobHandler;
import com.xxl.job.core.log.XxlJobLogger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.sql.rowset.serial.SerialException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author qry
 * @date 2019/9/4 14:37
 */
@JobHandler("refundOrderRefuseTimeOutHandler")
@Component
public class RefundOrderRefuseTimeOutHandler extends IJobHandler {

    @Autowired
    private OrderFeignService orderFeignService;

    @Autowired
    private ShxpRefundOrderService shxpRefundOrderService;

    @Override
    public ReturnT<String> execute(String s) throws Exception {
            XxlJobLogger.log("被拒绝状态超3天自动更新为取消状态任务开始");
            List<OmnipotentWrapper> wrappers = new ArrayList<>();
            wrappers.add(OmnipotentWrapper.setWrapper("eq", "status", RefundOrderStatusEnum.SELLER_REFUSE_REFUND.getCode()));
            wrappers.add(OmnipotentWrapper.setWrapper("ge",
                    "TIMESTAMPDIFF(SECOND,DATE_ADD(create_time,INTERVAL 3 DAY) ,now())", 0));
            Response<List<RefundOrder>> rs1 = orderFeignService.omniRefundOrder(wrappers);
            if (null == rs1 || rs1.getCode() != 200 || null == rs1.getData()) {
                throw new SerialException("feign调用查询要更新的数据异常");
            }
            for (RefundOrder ro:rs1.getData()){
                RefundOrderCancelParam param = new RefundOrderCancelParam();
                param.setRefundId(ro.getId());
                param.setCancelReason("");
                try{
                    shxpRefundOrderService.refundCancel(param);
                }catch (Exception e){
                    XxlJobLogger.log("被拒绝状态超3天自动更新为取消状态,退款单ID为"+ro.getId() +"更新失败",e);
                }
            }
        XxlJobLogger.log("被拒绝状态超3天自动更新为取消状态任务结束");
        return SUCCESS;
    }
}
